<template>
  <view>
    <YgSearch/>

    <tabs-bar 
      :list="tabList" 
      :current="currentTabIndex"
      @change="changeTab"
    />

    <view v-if="currentTabIndex === 0" class="list">
      <goodsItem
        v-for="item in goodsList"
        :key="item.goods_id"
        :data="item"
      />
    </view>
    <view v-if="currentTabIndex === 1">销量</view>
    <view v-if="currentTabIndex === 2">价格</view>
  </view>
</template>

<script>
  import tabsBar from "./components/tabsBar.vue";
  import goodsItem from "./components/goodsItem.vue";
  export default {
    components: { tabsBar, goodsItem },
    data() {
      return {
        tabList: [{ name: "综合" }, { name: "销量" }, { name: "价格" }],
        currentTabIndex: 0,
        goodsList: []
      };
    },
    onLoad(options) {
      console.log('跳转到列表页');
      console.log(options);
      this.total = 0
      this.pageConfig = {
        query: '',
        cid: options.cid || 12,
        pagenum: 1,
        pagesize: 10
      }
      this.loadPage()
    },
    onReachBottom() {
      console.log('到达底部');
      // 加载下一页
      // 不能盲目加载
      // 如果发现当前页面就是最后一页, 就要弹出提示, 否则再加载
      const maxPagenum = Math.ceil(this.total / this.pageConfig.pagesize)
      if (this.pageConfig.pagenum !== maxPagenum) {
        this.pageConfig.pagenum += 1
        this.loadPage()
      }else {
        uni.showToast({
          title: '我是有底线的',
          icon: 'none'
        })
      }
    },
    async onPullDownRefresh() {
      console.log('用户下拉');
      this.total = 0
      this.pageConfig.pagenum = 1
      this.goodsList = []
      // async 函数本身就会返回一个 promise 可以用 await 进行等待
      await this.loadPage()
      uni.stopPullDownRefresh()
    },
    methods: {
      async loadPage() {
        const {message} =await this.$u.get("/goods/search",this.pageConfig)
        // 储存数据列表
        this.goodsList = [
          ...this.goodsList,
          ...message.goods
        ]
        // 储存总条数
        this.total = message.total
      },
      changeTab(newIndex) {
        this.currentTabIndex = newIndex;
      },
    },
  };
</script>

<style lang="scss" scoped>

</style>